//
//  AreaViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/2/8.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "AreaViewController.h"

@interface AreaViewController (){
    NSArray *_oneArray;
    NSArray *_twoArray;
    NSArray *_threeArray;
    NSInteger _selectIndex1;
    NSInteger _selectIndex2;
    NSInteger _selectIndex3;
    NSDictionary *_areaDic;
    
    NSMutableArray *_selectList;
    
}

@property(nonatomic,weak) IBOutlet UITableView *tableView1;
@property(nonatomic,weak) IBOutlet UITableView *tableView2;
@property(nonatomic,weak) IBOutlet UITableView *tableView3;
@property(nonatomic,weak) IBOutlet UILabel *areaNameLabel;

@end

@implementation AreaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navStr = @"地址";
    _selectList = [[NSMutableArray alloc] initWithCapacity:10];
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [_tableView1 setTableFooterView:view];
    [_tableView2 setTableFooterView:view];
    [_tableView3 setTableFooterView:view];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 70, self.navView.frame.size.height-38 , 60, 30)];
    [rightBtn setTitle:@"确认" forState:UIControlStateNormal];
    
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"back_n.png"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(selectArea:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:rightBtn];
    
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"AreaData"];
    if (data != nil) {
        NSError *error = nil;
        
        id datadic = [NSJSONSerialization
                      
                      JSONObjectWithData:data
                      
                      options:NSJSONReadingMutableLeaves
                      
                      error:&error];
        _oneArray = (NSArray *)datadic;
    }
   
    if (_oneArray.count == 0 || [[GlobalData sharedGlobalData] isNewArea]) {
        [self getAreaData];
    }else{
//        _twoArray = _oneArray[0][@"CityList"];
//        _threeArray = _twoArray[0][@"AreaList"];
//        [_tableView1 reloadData];
//        [_tableView2 reloadData];
//        [_tableView3 reloadData];
//        _areaNameLabel.text = [NSString stringWithFormat:@"%@",_oneArray[0][@"AreaName"]];
    }
    // Do any additional setup after loading the view from its nib.
}

- (void)getAreaData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/area",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  
                                  [SVProgressHUD dismiss];
                                  
                                  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
                                  [[NSUserDefaults standardUserDefaults] setObject:jsonData forKey:@"AreaData"];                                  
                                  
                                  _oneArray = result;
                                  //        _twoArray = _oneArray[0][@"CityList"];
                                  //        _threeArray = _twoArray[0][@"AreaList"];
                                  [_tableView1 reloadData];
                                  //        [_tableView2 reloadData];
                                  //        [_tableView3 reloadData];
                                  _areaNameLabel.text = [NSString stringWithFormat:@"%@",_oneArray[0][@"AreaName"]];
                                  
                                  
                              }];
}

#pragma mark -
- (void)selectArea:(id)sender{
    if (_typeNum == 3) {
        NSString *city =@"";
        for (NSDictionary *dic in _selectList) {
            city = [NSString stringWithFormat:@"%@,%@",city,dic[@"AreaName"]];
        }
        if ([_delegate respondsToSelector:@selector(showAreaData:andArea:andAreaName:)]) {
            [_delegate showAreaData:_typeNum andArea:_areaDic andAreaName:city];
        }
    }else if (_typeNum == 4){
        if ([_delegate respondsToSelector:@selector(showAreaData:andAreaList:)]) {
            [_delegate showAreaData:_typeNum andAreaList:_selectList];
        }
    }
    else{
        NSArray *array = [_areaNameLabel.text componentsSeparatedByString:@"-"];
        if (array.count != 2) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择二级城市" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
        if ([_delegate respondsToSelector:@selector(showAreaData:andArea:andAreaName:)]) {
            [_delegate showAreaData:_typeNum andArea:_areaDic andAreaName:_areaNameLabel.text];
        }
    }
    [self backBtnAct:nil];
    
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_oneArray.count>0) {
        if (tableView == _tableView1) {
            return _oneArray.count;
        }
        
    }
    if (_twoArray.count>0) {
        if (tableView == _tableView2) {
            return _twoArray.count;
        }
    }
    if (_threeArray.count>0) {
        if (tableView == _tableView3) {
            return _threeArray.count;
        }
    }
    
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        [cell.textLabel setTextColor:[UIColor whiteColor]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell setBackgroundColor:[UIColor grayColor]];
    [cell setAccessoryType:UITableViewCellAccessoryNone];

    if (tableView == _tableView1) {
        cell.textLabel.text = [_oneArray objectAtIndex:indexPath.row][@"AreaName"];
    }
    else if (tableView == _tableView2)
    {
        for (NSDictionary *dic in _selectList) {
            if ([dic isEqualToDictionary:[_twoArray objectAtIndex:indexPath.row]]) {
                [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
                break;
            }
        }
        cell.textLabel.text = [_twoArray objectAtIndex:indexPath.row][@"AreaName"];
    }else{
        cell.textLabel.text = [_threeArray objectAtIndex:indexPath.row][@"AreaName"];
    }
    
    return cell;
    
    
    
}

#pragma mark - Tableview Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == _tableView1) {
        
        // 取消前一个选中的，就是单选啦
        
        NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_selectIndex1 inSection:0];
        
        UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastIndex];
        
        lastCell.backgroundColor = [UIColor grayColor];
        _selectIndex1 = indexPath.row;
        
        // 选中操作
        
        UITableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
        cell.backgroundColor = RGB(47, 82, 132);
        
        //下一级数据
        _twoArray = nil;
        _twoArray = _oneArray[indexPath.row][@"CityList"];
        _threeArray = _twoArray[0][@"AreaList"];
        [self.tableView2 reloadData];
        [self.tableView3 reloadData];
        _areaDic = _oneArray[indexPath.row];
        _areaNameLabel.text = _oneArray[indexPath.row][@"AreaName"];
        _selectIndex2 = 0;
        _selectIndex3 = 0;
    }
    else if (tableView == _tableView2) {
        if (_typeNum == 3 || _typeNum == 4) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (cell.accessoryType == UITableViewCellAccessoryNone){
                if (_typeNum == 3) {
                    if (_selectList.count >= 5) {
                        [SVProgressHUD showInfoWithStatus:@"最多只能选5个城市"];
                        return;
                    }
                }
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                [_selectList addObject:_twoArray[indexPath.row]];
            }
            else{
                [_selectList removeObject:_twoArray[indexPath.row]];
                cell.accessoryType = UITableViewCellAccessoryNone;
            }

            
        }else{
            // 取消前一个选中的，就是单选啦
            
            NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_selectIndex2 inSection:0];
            
            UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastIndex];
            
            lastCell.backgroundColor = [UIColor grayColor];
            _selectIndex2 = indexPath.row;
            
            // 选中操作
            
            UITableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
            cell.backgroundColor = RGB(47, 82, 132);
        }
            //下一级数据
            _threeArray = nil;
            _areaDic = _twoArray[indexPath.row];

            _threeArray = _twoArray[indexPath.row][@"AreaList"];
            [self.tableView3 reloadData];
            NSArray *array = [_areaNameLabel.text componentsSeparatedByString:@"-"];
            _areaNameLabel.text = [NSString stringWithFormat:@"%@-%@",array[0],_twoArray[indexPath.row][@"AreaName"]];
            _selectIndex3 = 0;
    }else if (tableView == _tableView3){
        // 取消前一个选中的，就是单选啦
        
        NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_selectIndex3 inSection:0];
        
        UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastIndex];
        
        lastCell.backgroundColor = [UIColor grayColor];
        _selectIndex3 = indexPath.row;
        
        // 选中操作
        
        UITableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
        cell.backgroundColor = RGB(47, 82, 132);
        
        _areaDic = _threeArray[indexPath.row];
        NSArray *array = [_areaNameLabel.text componentsSeparatedByString:@"-"];
        NSString *city;
        if (array.count == 1) {
            city = _twoArray[indexPath.row][@"AreaName"];
        }else{
            city = array[1];
        }
        _areaNameLabel.text =[NSString stringWithFormat:@"%@-%@-%@",array[0],city,_threeArray[indexPath.row][@"AreaName"]];
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
